/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libgp2x.

    libgp2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libgp2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libgp2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "gp2x_internal.h"

unsigned short* GP2x_screens[2];
unsigned long GP2x_screen_addr[2];

void GP2x_video_init() {
    GP2x_screens[0] = (unsigned short*)(0x01101000 + GP2x_upper_memory);
    GP2x_screen_addr[0] = (unsigned long)0x03101000;
    GP2x_screens[1] = (unsigned short*)(0x01381000 + GP2x_upper_memory);
    GP2x_screen_addr[1] = (unsigned long)0x03381000;

#ifdef HOST_GP2x
    GP2x_screen = GP2x_screens[0];
#else
    GP2x_screen = GP2x_screens[1];
#endif

    GP2x_flip_unsync();
}

void GP2x_flip() {
    GP2x_video_vsync();
    GP2x_flip_unsync();
}

void GP2x_flip_unsync() {
#ifdef HOST_PC
    if(GP2x_screen == GP2x_screens[0]) {
        GP2x_screen = GP2x_screens[1];
#endif
        GP2x_register(0x290E) = GP2x_register(0x2912) = GP2x_screen_addr[0] & 0xFFFF;
        GP2x_register(0x2910) = GP2x_register(0x2914) = GP2x_screen_addr[0] >> 16;
#ifdef HOST_PC
    } else {
        GP2x_screen = GP2x_screens[0];
        GP2x_register(0x290E) = GP2x_register(0x2912) = GP2x_screen_addr[1] & 0xFFFF;
        GP2x_register(0x2910) = GP2x_register(0x2914) = GP2x_screen_addr[1] >> 16;
    }
#endif

    while(~GP2x_register(GP2x_REG_SCREEN_SYNC) & (1 << 4));
}

void GP2x_video_hsync() {
    while(GP2x_register(GP2x_REG_SCREEN_SYNC) & (1 << 5));
}

void GP2x_video_vsync() {
    while(GP2x_register(GP2x_REG_SCREEN_SYNC) & (1 << 4));
}
